{% extends "base.html" %}

{% block content %}
<div class="card">
    <h2><i class="fas fa-sync-alt"></i> 检测更新</h2>
    
    <div id="update-status">
        <div class="loading">检查更新中...</div>
    </div>
    
    <div id="releases-list" style="display: none; margin-top: 20px;">
        <h3>最近更新 
            <button onclick="toggleReleasesList()" class="btn btn-sm btn-secondary" style="margin-left: 10px;">
                <i class="fas fa-chevron-up"></i> 收起
            </button>
        </h3>
        <div class="releases-container"></div>
    </div>
    
    <div class="form-actions">
        <button onclick="checkForUpdates()" class="btn btn-primary">
            <i class="fas fa-sync"></i> 检查更新
        </button>
        <button onclick="viewAllReleases()" class="btn btn-info">
            <i class="fas fa-list"></i> 查看所有版本
        </button>
        <button onclick="manualBackup()" class="btn btn-info">
            <i class="fas fa-copy"></i> 手动备份
        </button>
    </div>
</div>

<div class="card" style="margin-top: 20px;">
    <h2><i class="fas fa-history"></i> 版本回退</h2>
    
    <div id="backups-list">
        <div class="loading">加载备份列表...</div>
    </div>
    
    <div class="form-actions">
        <button onclick="loadBackups()" class="btn btn-info">
            <i class="fas fa-refresh"></i> 刷新备份列表
        </button>
    </div>
</div>

<!-- 版本详情模态框 -->
<div id="versionDetailModal" class="modal" style="display: none;">
    <div class="modal-content" style="max-width: 700px;">
        <div class="modal-header">
            <h3 id="versionDetailTitle">版本详情</h3>
            <span class="close" onclick="closeModal('versionDetailModal')">×</span>
        </div>
        <div class="modal-body">
            <div id="version-detail-content" class="loading">加载版本详情中...</div>
            <div class="modal-actions" style="margin-top: 20px; text-align: center;">
                <button onclick="performUpdate()" class="btn btn-success">
                    <i class="fas fa-download"></i> 更新到此版本
                </button>
                <button onclick="closeModal('versionDetailModal')" class="btn btn-secondary">
                    <i class="fas fa-times"></i> 关闭
                </button>
            </div>
        </div>
    </div>
</div>

<style>
/* 更新状态样式 */
.update-available, .no-update, .error {
    padding: 20px;
    border-radius: 8px;
    margin: 15px 0;
}

.update-available {
    background: linear-gradient(135deg, #e8f5e8, #c8e6c9);
    border: 1px solid #4CAF50;
}

.no-update {
    background: #f5f5f5;
    border: 1px solid #ddd;
}

.error {
    background: #ffebee;
    border: 1px solid #F44336;
}

/* 发布卡片样式 */
.release-card {
    background: white;
    border: 1px solid #ddd;
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 15px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.release-card.current-release {
    border-color: #4CAF50;
    background: #e8f5e8;
}

.release-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 10px;
}

.release-title {
    flex: 1;
}

.release-actions {
    flex-shrink: 0;
}

.tag {
    background: linear-gradient(45deg, #2196F3, #64B5F6);
    color: white;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 0.9em;
    font-weight: 500;
}

.current-badge {
    background: linear-gradient(45deg, #4CAF50, #81C784);
    color: white;
    padding: 6px 14px;
    border-radius: 20px;
    font-size: 0.9em;
    font-weight: 500;
}

.release-date {
    color: #666;
    font-size: 0.9em;
    margin-top: 5px;
}

/* 备份卡片样式 */
.backup-card {
    background: white;
    border: 1px solid #ddd;
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 15px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.backup-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 10px;
}

.backup-filename {
    font-weight: 600;
    color: #333;
    font-size: 1.1em;
    margin-bottom: 5px;
}

.backup-version {
    background: #2196F3;
    color: white;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 0.8em;
    margin-top: 5px;
    display: inline-block;
}

.backup-details {
    margin-top: 10px;
    padding-top: 10px;
    border-top: 1px solid #eee;
}

.backup-detail {
    display: flex;
    justify-content: space-between;
    margin-bottom: 5px;
    font-size: 0.9em;
}

.backup-detail strong {
    color: #666;
    margin-right: 10px;
}

.backup-actions {
    margin-top: 15px;
    text-align: right;
}

/* 折叠内容样式 */
.toggle-section {
    margin: 10px 0;
}

.toggle-btn {
    background: linear-gradient(45deg, #66b3ff, #8ecfff);
    color: white;
    border: none;
    padding: 8px 16px;
    border-radius: 6px;
    cursor: pointer;
    font-size: 14px;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    transition: all 0.3s ease;
    box-shadow: 0 2px 4px rgba(102, 179, 255, 0.3);
}

.toggle-btn:hover {
    background: linear-gradient(45deg, #4d94ff, #70b8ff);
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(102, 179, 255, 0.4);
}

.collapsible-content {
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.3s ease-out;
}

.collapsible-content.expanded {
    max-height: 500px;
}

/* 更新内容和资源文件样式 */
.release-notes {
    margin: 10px 0;
    padding: 15px;
    background: #f8f9fa;
    border-radius: 6px;
    border-left: 4px solid #2196F3;
}

.release-notes pre {
    background: white;
    padding: 15px;
    border-radius: 5px;
    border: 1px solid #ddd;
    max-height: 200px;
    overflow-y: auto;
    white-space: pre-wrap;
    font-family: 'Consolas', 'Monaco', monospace;
    line-height: 1.4;
}

.assets-list {
    margin-top: 10px;
    padding: 15px;
    background: #f8f9fa;
    border-radius: 6px;
    border-left: 4px solid #FF9800;
}

.asset-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
    border-bottom: 1px solid #eee;
    transition: background-color 0.3s ease;
}

.asset-item:last-child {
    border-bottom: none;
}

.asset-item:hover {
    background-color: #e3f2fd;
}

.asset-name {
    font-weight: 500;
    color: #333;
    flex: 1;
}

.asset-size {
    color: #666;
    font-size: 12px;
    margin-right: 15px;
}

.asset-download {
    background: linear-gradient(45deg, #4CAF50, #81C784);
    color: white;
    text-decoration: none;
    padding: 6px 12px;
    border-radius: 4px;
    font-size: 12px;
    transition: all 0.3s ease;
}

.asset-download:hover {
    background: linear-gradient(45deg, #388E3C, #66BB6A);
    transform: translateY(-1px);
    box-shadow: 0 2px 4px rgba(76, 175, 80, 0.3);
}

/* 模态框样式 */
.modal {
    position: fixed;
    z-index: 1000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.5);
    display: flex;
    align-items: center;
    justify-content: center;
}

.modal-content {
    background-color: white;
    border-radius: 12px;
    width: 90%;
    max-width: 600px;
    max-height: 80vh;
    overflow-y: auto;
    box-shadow: 0 4px 20px rgba(0,0,0,0.2);
}

.modal-header {
    padding: 20px;
    border-bottom: 1px solid #eee;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.modal-header h3 {
    margin: 0;
    color: #333;
}

.close {
    color: #aaa;
    font-size: 28px;
    font-weight: bold;
    cursor: pointer;
    transition: color 0.3s ease;
}

.close:hover {
    color: #333;
}

.modal-body {
    padding: 20px;
}

.release-detail {
    max-height: 400px;
    overflow-y: auto;
}

.release-header {
    margin-bottom: 15px;
    padding-bottom: 15px;
    border-bottom: 1px solid #eee;
}

.release-assets {
    margin-top: 15px;
}

.release-assets h5 {
    margin-bottom: 10px;
    color: #333;
}

.modal-actions {
    display: flex;
    gap: 10px;
    justify-content: center;
    margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .release-header {
        flex-direction: column;
        gap: 10px;
    }
    
    .release-actions {
        align-self: flex-start;
    }
    
    .modal-content {
        width: 95%;
        margin: 20px;
    }
    
    .asset-item {
        flex-direction: column;
        align-items: flex-start;
        gap: 8px;
    }
    
    .asset-size {
        margin-right: 0;
    }
    
    .asset-download {
        align-self: flex-end;
    }
    
    .backup-details {
        grid-template-columns: 1fr;
    }
    
    .backup-actions {
        flex-direction: column;
    }
}
</style>

<script>
// 全局变量
let releasesListExpanded = false;
let selectedVersion = null;

async function checkForUpdates() {
    const statusDiv = document.getElementById('update-status');
    statusDiv.innerHTML = '<div class="loading">检查更新中...</div>';
    
    try {
        const response = await fetch('/check_update');
        const data = await response.json();
        
        if (data.success) {
            if (data.update_available) {
                statusDiv.innerHTML = `
                    <div class="update-available">
                        <h3 style="color: #4CAF50;">🎉 发现新版本！</h3>
                        <p>当前版本: ${data.current_version}</p>
                        <p>最新版本: <strong>${data.latest_version}</strong></p>
                        <p>发布时间: ${new Date(data.published_at).toLocaleString()}</p>
                        
                        <div class="toggle-section">
                            <button class="toggle-btn" onclick="toggleSection(this, 'changelog')">
                                <i class="fas fa-chevron-down"></i> 显示更新内容
                            </button>
                            <div id="changelog" class="collapsible-content">
                                <div class="release-notes">
                                    <h4>更新内容:</h4>
                                    <pre>${data.changelog}</pre>
                                </div>
                            </div>
                        </div>
                        
                        <button onclick="performUpdate('${data.latest_version}')" class="btn btn-success">
                            <i class="fas fa-download"></i> 立即更新
                        </button>
                    </div>
                `;
            } else {
                statusDiv.innerHTML = `
                    <div class="no-update">
                        <h3 style="color: #666;">✅ 当前已是最新版本</h3>
                        <p>当前版本: ${data.current_version}</p>
                    </div>
                `;
            }
        } else {
            statusDiv.innerHTML = `<div class="error">❌ 检查更新失败: ${data.error}</div>`;
        }
    } catch (error) {
        statusDiv.innerHTML = `<div class="error">❌ 请求失败: ${error}</div>`;
    }
}

async function viewAllReleases() {
    const releasesDiv = document.getElementById('releases-list');
    const container = releasesDiv.querySelector('.releases-container');
    container.innerHTML = '<div class="loading">加载中...</div>';
    releasesDiv.style.display = 'block';
    releasesListExpanded = true;
    
    try {
        const response = await fetch('/get_releases');
        const data = await response.json();
        
        if (data.success) {
            let html = '';
            data.releases.forEach(release => {
                const isCurrent = release.tag_name === data.current_version;
                html += `
                    <div class="release-card ${isCurrent ? 'current-release' : ''}">
                        <div class="release-header">
                            <div class="release-title">
                                <h4>${release.name}</h4>
                                <span class="tag">${release.tag_name}</span>
                                <p class="release-date">${new Date(release.published_at).toLocaleString()}</p>
                            </div>
                            <div class="release-actions">
                                ${isCurrent ? 
                                    '<span class="current-badge">当前版本</span>' : 
                                    `<button onclick="performUpdate('${release.tag_name}')" class="btn btn-success btn-sm">
                                        <i class="fas fa-download"></i> 更新
                                    </button>`
                                }
                            </div>
                        </div>
                        
                        <div class="toggle-section">
                            <button class="toggle-btn" onclick="toggleSection(this, 'notes-${release.tag_name}')">
                                <i class="fas fa-chevron-down"></i> 显示更新内容
                            </button>
                            <div id="notes-${release.tag_name}" class="collapsible-content">
                                <div class="release-notes">
                                    <pre>${release.body}</pre>
                                </div>
                            </div>
                        </div>
                        
                        ${release.assets && release.assets.length > 0 ? `
                        <div class="toggle-section">
                            <button class="toggle-btn" onclick="toggleSection(this, 'assets-${release.tag_name}')">
                                <i class="fas fa-chevron-down"></i> 显示资源文件 (${release.assets.length})
                            </button>
                            <div id="assets-${release.tag_name}" class="collapsible-content">
                                <div class="assets-list">
                                    ${release.assets.map(asset => `
                                        <div class="asset-item">
                                            <span class="asset-name">${asset.name}</span>
                                            <span class="asset-size">${formatFileSize(asset.size)}</span>
                                            <a href="${asset.browser_download_url}" target="_blank" class="asset-download">
                                                <i class="fas fa-download"></i> 下载
                                            </a>
                                        </div>
                                    `).join('')}
                                </div>
                            </div>
                        </div>
                        ` : ''}
                    </div>
                `;
            });
            container.innerHTML = html;
        } else {
            container.innerHTML = `<div class="error">加载失败: ${data.error}</div>`;
        }
    } catch (error) {
        container.innerHTML = `<div class="error">请求失败: ${error}</div>`;
    }
}

function toggleReleasesList() {
    const releasesDiv = document.getElementById('releases-list');
    const toggleBtn = releasesDiv.querySelector('button');
    const icon = toggleBtn.querySelector('i');
    
    if (releasesListExpanded) {
        releasesDiv.style.display = 'none';
        icon.className = 'fas fa-chevron-down';
        toggleBtn.innerHTML = '<i class="fas fa-chevron-down"></i> 展开';
        releasesListExpanded = false;
    } else {
        releasesDiv.style.display = 'block';
        icon.className = 'fas fa-chevron-up';
        toggleBtn.innerHTML = '<i class="fas fa-chevron-up"></i> 收起';
        releasesListExpanded = true;
    }
}

function toggleSection(button, contentId) {
    const content = document.getElementById(contentId);
    const icon = button.querySelector('i');
    
    if (content.classList.contains('expanded')) {
        content.classList.remove('expanded');
        icon.className = 'fas fa-chevron-down';
    } else {
        content.classList.add('expanded');
        icon.className = 'fas fa-chevron-up';
    }
}

function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

async function performUpdate(releaseTag) {
    if (!confirm(`确定要更新到版本 ${releaseTag} 吗？\n\n建议先备份数据。`)) {
        return;
    }
    
    const statusDiv = document.getElementById('update-status');
    statusDiv.innerHTML = '<div class="loading">更新中，请查看终端日志...</div>';
    
    try {
        const response = await fetch('/perform_update', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ release_tag: releaseTag })
        });
        
        const data = await response.json();
        
        if (data.success) {
            statusDiv.innerHTML = `
                <div class="success">
                    <h3 style="color: #4CAF50;">✅ 更新成功！</h3>
                    <p>${data.message}</p>
                    <p>请重启机器人使更新生效</p>
                </div>
            `;
        } else {
            statusDiv.innerHTML = `
                <div class="error">
                    <h3 style="color: #F44336;">❌ 更新失败</h3>
                    <p>${data.message}</p>
                </div>
            `;
        }
    } catch (error) {
        statusDiv.innerHTML = `
            <div class="error">
                <h3 style="color: #4CAF50;">⏳ 更新进行中，连接已断开，重启后刷新页面即可</h3>
                <p>${error}</p>
            </div>
        `;
    }
}

// 加载备份列表函数
async function loadBackups() {
    const backupsDiv = document.getElementById('backups-list');
    backupsDiv.innerHTML = '<div class="loading">加载备份列表中...</div>';
    
    try {
        const response = await fetch('/get_backups');
        const data = await response.json();
        
        if (data.success) {
            if (data.backups.length > 0) {
                let html = '<div class="backups-container">';
                data.backups.forEach(backup => {
                    const sizeMB = (backup.size / (1024 * 1024)).toFixed(2);
                    const createdDate = new Date(backup.created_at);
                    
                    html += `
                        <div class="backup-card">
                            <div class="backup-header">
                                <div class="backup-filename" style="font-size: clamp(0.7em, 3.5vw, 0.9em); word-break: break-all; max-width: 100%;">${backup.filename}</div>
                            </div>
                            <div class="backup-details">
                                <div class="backup-detail">
                                    <strong>版本:</strong>
                                    <span class="backup-version">${backup.version}</span>
                                </div>
                                <div class="backup-detail">
                                    <strong>创建时间:</strong>
                                    ${createdDate.toLocaleString()}
                                </div>
                                <div class="backup-detail">
                                    <strong>文件大小:</strong>
                                    ${sizeMB} MB
                                </div>
                            </div>
                            <div class="backup-actions">
                                <button onclick="confirmRestore('${backup.filename}')" class="btn btn-warning">
                                    <i class="fas fa-undo"></i> 恢复到此版本
                                </button>
                                <button onclick="downloadBackup('${backup.filename}')" class="btn btn-info">
                                    <i class="fas fa-download"></i> 下载
                                </button>
                                <button onclick="confirmDeleteBackup('${backup.filename}')" class="btn btn-danger">
                                    <i class="fas fa-trash"></i> 删除
                                </button>
                            </div>
                        </div>
                    `;
                });
                html += '</div>';
                backupsDiv.innerHTML = html;
            } else {
                backupsDiv.innerHTML = '<div class="no-backups">暂无备份文件</div>';
            }
        } else {
            backupsDiv.innerHTML = `<div class="error">加载备份失败: ${data.error}</div>`;
        }
    } catch (error) {
        backupsDiv.innerHTML = `<div class="error">请求失败: ${error}</div>`;
    }
}

// 确认恢复备份函数
async function confirmRestore(backupFilename) {
    if (!confirm(`确定要从备份 ${backupFilename} 恢复吗？\n\n这将覆盖当前文件，操作不可逆！`)) {
        return;
    }
    
    const statusDiv = document.getElementById('update-status');
    statusDiv.innerHTML = '<div class="loading">恢复中，请查看终端日志...</div>';
    
    try {
        const response = await fetch('/restore_backup', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ backup_filename: backupFilename })
        });
        
        const data = await response.json();
        
        if (data.success) {
            statusDiv.innerHTML = `
                <div class="success">
                    <h3 style="color: #4CAF50;">✅ 恢复成功！</h3>
                    <p>${data.message}</p>
                    <p>请重启机器人使恢复生效</p>
                </div>
            `;
        } else {
            statusDiv.innerHTML = `
                <div class="error">
                    <h3 style="color: #F44336;">❌ 恢复失败</h3>
                    <p>${data.error}</p>
                </div>
            `;
        }
    } catch (error) {
        statusDiv.innerHTML = `
            <div class="error">
                <h3 style="color: #4CAF50;">⏳ 恢复进行中，连接已断开，重启后刷新页面即可</h3>
                <p>${error}</p>
            </div>
        `;
    }
}

// 手动备份函数
async function manualBackup() {
    const statusDiv = document.getElementById('update-status');
    statusDiv.innerHTML = '<div class="loading">正在创建手动备份，请稍候...</div>';
    
    try {
        const response = await fetch('/manual_backup', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            }
        });
        
        const data = await response.json();
        
        if (data.success) {
            statusDiv.innerHTML = `
                <div class="success">
                    <h3 style="color: #4CAF50;">✅ 手动备份成功！</h3>
                    <p>${data.message}</p>
                    <div style="margin-top: 15px; padding: 10px; background: #e8f5e8; border-radius: 5px; 
                         word-break: break-all; overflow-wrap: break-word;">
                        <p style="margin: 5px 0; word-break: break-word;"><strong>插件备份:</strong> ${data.plugin_backup}</p>
                        <p style="margin: 5px 0; word-break: break-word;"><strong>配置备份:</strong> ${data.config_backup}</p>
                    </div>
                    <p style="margin-top: 10px; color: #666; font-size: 0.9em;">
                        备份文件保存在 data/backups/ 和 data/config_backups/ 目录中
                    </p>
                </div>
            `;
            
            // 刷新备份列表
            loadBackups();
        } else {
            statusDiv.innerHTML = `
                <div class="error">
                    <h3 style="color: #F44336;">❌ 手动备份失败</h3>
                    <p>${data.error}</p>
                </div>
            `;
        }
    } catch (error) {
        statusDiv.innerHTML = `
            <div class="error">
                <h3 style="color: #F44336;">❌ 请求失败</h3>
                <p>${error}</p>
            </div>
        `;
    }
}

// 下载备份文件函数
async function downloadBackup(backupFilename) {
    // 直接在新窗口打开下载链接
    window.open(`/download_backup/${encodeURIComponent(backupFilename)}`, '_blank');
    
    // 显示成功消息
    const statusDiv = document.getElementById('update-status');
    statusDiv.innerHTML = `
        <div class="success">
            <h3 style="color: #4CAF50;">✅ 下载开始</h3>
            <p>备份文件 ${backupFilename} 正在下载中...</p>
        </div>
    `;
}

// 确认删除备份函数
async function confirmDeleteBackup(backupFilename) {
    if (!confirm(`确定要删除备份文件 ${backupFilename} 吗？\n\n此操作不可撤销！`)) {
        return;
    }
    
    try {
        const response = await fetch('/delete_backup', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ backup_filename: backupFilename })
        });
        
        const data = await response.json();
        
        if (data.success) {
            alert('✅ 备份文件删除成功');
            loadBackups(); // 重新加载备份列表
        } else {
            alert(`❌ 删除失败: ${data.error}`);
        }
    } catch (error) {
        alert(`❌ 请求失败: ${error}`);
    }
}

function closeModal(modalId) {
    document.getElementById(modalId).style.display = 'none';
}

// 页面加载时自动检查更新和加载备份列表
document.addEventListener('DOMContentLoaded', function() {
    checkForUpdates();
    loadBackups();
});

// 添加全局点击事件关闭模态框
document.addEventListener('click', function(event) {
    const modals = document.querySelectorAll('.modal');
    modals.forEach(modal => {
        if (event.target === modal) {
            modal.style.display = 'none';
        }
    });
});
</script>
{% endblock %}
